package com.lq.service;

import com.lq.common.Constants;
import com.lq.common.SqlConstant;
import com.lq.utils.UniqueNumberUtil;
import com.lq.utils.jdbc.Jdbc;
import com.lq.utils.jdbc.LqJdbcFactory;
import com.lq.utils.jdbc.LqPiLiang;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.log4j.Logger;

import java.util.*;

public class DataGpibService {

    public static Logger logRecordGpib = Logger.getLogger("recordGpibDB");
    public static Integer pageSize = 2000;

    public static void handleRecord() {
        int threadCount = 1;
        for (int t = 0; t < threadCount; t++) {
            new Thread(() -> {
                try {
                    //先判断一下有要处理的数据没
                    ListOrderedMap orderedMap = Jdbc.findOne("select count(*) as number from  gpib_record where  exclusive <> '1' or exclusive is null", new Object[]{});
                    if (orderedMap != null && !"0".equals(orderedMap.get("number") + "")) {
                        List<ListOrderedMap> selectPointList = Jdbc.find(SqlConstant.SQL_SELECT_EQUIPMENT_CONFIG, new Object[]{});
                        Map<String, ListOrderedMap> mapPoint = new HashMap();
                        selectPointList.stream().forEach(l -> {
                            String uniqueNumber = UniqueNumberUtil.getNumber(l.get("device_host_id").toString());
                            if ("513".equals(uniqueNumber) || "511".equals(uniqueNumber)) {
                                mapPoint.put(l.get("company_code").toString() + "_" + l.get("area_code").toString() + "_" + l.get("device_host_id").toString() + "_" + l.get("measuring_point_addr").toString(), l);
                            } else {
                                mapPoint.put(l.get("company_code").toString() + "_" + l.get("area_code").toString() + "_" + l.get("device_id").toString(), l);
                                //因为定位数据都是跟着主机走了，所以要在这个地方重新放一下
                                mapPoint.put("GPS" + "_" + l.get("company_code").toString() + "_" + l.get("area_code").toString() + "_" + l.get("device_host_id").toString(), l);
                            }
                        });

                        String zhId = "0";
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

                        long startTime = System.currentTimeMillis();
                        logRecordGpib.info("开始取出MaxID。");
                        List<ListOrderedMap> listMax = Jdbc.find("select * from ypsyscfg where ypsection='recordGpib_db' and ypitemname='lq' for update");
                        logRecordGpib.info("成功取出MaxID。 耗时：" + (System.currentTimeMillis() - startTime) + "ms");

                        long maxId = Long.valueOf(listMax.get(0).get("ypitemvalue").toString());
                        logRecordGpib.info(("开始从【" + maxId + "】标记【" + pageSize + "】条数据。"));
                        startTime = System.currentTimeMillis();
                        int result = Jdbc.execute("update gpib_record set exclusive= ? where id>? and exclusive <> '1' or exclusive is null limit ?", new Object[]{uuid, maxId, pageSize});

                        List<ListOrderedMap> list = new ArrayList();
                        if (result > 0) {
                            logRecordGpib.info("从【" + maxId + "】标记【" + pageSize + "】条数据成功。耗时：" + (System.currentTimeMillis() - startTime) + "ms");
                            logRecordGpib.info("开始取出【" + pageSize + "】条数据。");
                            startTime = System.currentTimeMillis();
                            list = Jdbc.find(SqlConstant.SQL_SELECT_GPIB_RECORD, new Object[]{uuid});
                            logRecordGpib.info("成功取出【" + pageSize + "】条数据。耗时：" + (System.currentTimeMillis() - startTime) + "ms");
                        }

                        List<Object[]> listAlarms = new ArrayList();
                        List<Object[]> listRecord = new ArrayList();
                        List<Object[]> listGps = new ArrayList();
                        List<Object[]> listFail = new ArrayList();
                        if (list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                Map dataMap = list.get(i);
                                //数据类型
                                String dataType = dataMap.get("data_type") + "";
                                //编码类型
                                String typeNumber = dataMap.get("type_number") + "";
                                //企业编号
                                String companyCode = dataMap.get("company_code") + "";
                                //库区编号
                                String areaCode = dataMap.get("area_code") + "";
                                //测点地址
                                String ipAddr = dataMap.get("measuring_point_addr") + "";
                                //主机编号
                                String DevHostID = dataMap.get("device_host_id") + "";
                                //设备编号
                                String DevID = dataMap.get("device_id") + "";
                                //数据时间
                                String date = dataMap.get("date") + "";

                                Map point = null;
                                Map pointGps = null;
                                if ("513".equals(typeNumber) || "511".equals(typeNumber)) {
                                    point = mapPoint.get(companyCode + "_" + areaCode + "_" + DevHostID + "_" + ipAddr);
                                } else {
                                    point = mapPoint.get(companyCode + "_" + areaCode + "_" + DevID);
                                    pointGps = mapPoint.get("GPS" + "_" + companyCode + "_" + areaCode + "_" + DevHostID);
                                }
                                if (Constants.COLL_NAME_GPS.equals(dataType)) {
                                    if (pointGps != null) {
                                        Object[] obj = new Object[]{companyCode, areaCode, point.get("measuring_point_name"), ipAddr, date, point.get("storehouse_property"), dataMap.get("gps_longitude"), dataMap.get("gps_latitude"), DevHostID, Constants.PUSH_TYPE};
                                        listGps.add(obj);
                                    } else {
                                        Object[] obj = new Object[]{"000", dataMap.get("id")};
                                        listFail.add(obj);
                                    }
                                } else {
                                    if (point != null) {
                                        if (Constants.COLL_NAME_RECORD.equals(dataType)) {
                                            String emptyKu = "";
                                            if ("1".equals(point.get("state").toString())) {
                                                emptyKu = "空库";
                                            }
                                            Object[] obj = new Object[]{companyCode, areaCode, point.get("measuring_point_name"), ipAddr, dataMap.get("temperature"), dataMap.get("humidity"), date, point.get("storehouse_property"), dataMap.get("gps_longitude"), dataMap.get("gps_latitude"), emptyKu, DevHostID, Constants.PUSH_TYPE};
                                            listRecord.add(obj);
                                        } else if (Constants.COLL_NAME_RECORD_ALARMS.equals(dataType)) {
                                            if ("0".equals(point.get("state").toString())) {
                                                Object[] obj = new Object[]{companyCode, areaCode, point.get("measuring_point_name"), ipAddr,
                                                        dataMap.get("temperature_alarms_upper_limit"), dataMap.get("temperature_alarms_lower_limit"), dataMap.get("temperature_warning_upper_limit"), dataMap.get("temperature_warning_lower_limit"),
                                                        dataMap.get("humidity_alarms_upper_limit"), dataMap.get("humidity_alarms_lower_limit"), dataMap.get("humidity_warning_upper_limit"), dataMap.get("humidity_warning_lower_limit"),
                                                        dataMap.get("temperature"), dataMap.get("humidity"), dataMap.get("gps_longitude"), dataMap.get("gps_latitude"), date, point.get("storehouse_property"), dataMap.get("record_remark"), DevHostID, Constants.PUSH_TYPE};
                                                listAlarms.add(obj);
                                            }
                                        }
                                    } else {
                                        Object[] obj = new Object[]{"000", dataMap.get("id")};
                                        listFail.add(obj);
                                    }
                                }
                            }
                        }

                        //批量插入数据
                        Jdbc.piliang(SqlConstant.SQL_INSERT_RECORD, new LqPiLiang() {
                            public void piliang(LqJdbcFactory jdbc) {
                                listRecord.forEach(l -> {
                                    jdbc.executeS(l);
                                });
                            }
                        });
                        //批量插入数据
                        Jdbc.piliang(SqlConstant.SQL_INSERT_RECORD_ALARMS, new LqPiLiang() {
                            public void piliang(LqJdbcFactory jdbc) {
                                listAlarms.forEach(l -> {
                                    jdbc.executeS(l);
                                });
                            }
                        });
                        //批量插入数据
                        Jdbc.piliang(SqlConstant.SQL_INSERT_GPS, new LqPiLiang() {
                            public void piliang(LqJdbcFactory jdbc) {
                                listGps.forEach(l -> {
                                    jdbc.executeS(l);
                                });
                            }
                        });
                        Jdbc.piliang(SqlConstant.SQL_UPDATE_GPIB_RECORD, new LqPiLiang() {
                            public void piliang(LqJdbcFactory jdbc) {
                                listFail.forEach(l -> {
                                    jdbc.executeS(l);
                                });
                            }
                        });

                        logRecordGpib.info("成功插入历史分表数据。耗时：" + (System.currentTimeMillis() - startTime) + "ms");
                        logRecordGpib.info("开始将标记更新为1和MaxId进行变更【" + zhId + "】。");
                        //处理成功将uuid值改为1
                        Jdbc.execute("update gpib_record set exclusive ='1' where exclusive = ?", new Object[]{uuid});
                        Jdbc.execute("update ypsyscfg set ypitemvalue = ? where ypsection = 'recordGpib_db' and ypitemname = 'lq' ", new Object[]{zhId});
                        logRecordGpib.info("标记已更新为1和MaxId已变更【" + zhId + "】成功。耗时：" + (System.currentTimeMillis() - startTime) + "ms");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
